import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import Taro, { FC, useRouter } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtInputNumber, AtIcon, AtCountdown } from 'taro-ui'
import OrderBtnState from '@/components/OrderBtnState'
import Payment from '@/components/Payment'
import Modal from '@/components/Modal'
import { useSelector } from 'react-redux'
import { AddressObj, OrderDetail } from '@/constants/commonType'

import api from '@/services/config/index'
import { countDown, CountDownReturn, showToast } from '@/utils/common'
import './index.scss'

interface DefalutAddress {
  addressName: string
  addressMobile: string
  addressDetail: string
  // 地址id
  addressId: string
}
type useSelectorState = {
  address: AddressObj
}
interface ConfirmParams {
  type: number | string
  orderId: string
}
const OrderDetails: FC = () => {
  const address = useSelector((state: useSelectorState) => state.address)
  const [orderNum, setOrderNum] = useState<number>(1)
  const [showPay, setShowPay] = useState<boolean>(false)
  const [orderDetail, setOrderDetail] = useState<OrderDetail>({
    title: '',
    imagePath: [
      {
        imagePath: ''
      }
    ],
    shareDetail: {
      // 积分
      sharePoints: '',
      // 押金（押积分）
      deposit: '',
      // 库存
      inventory: '',
      // 是否需要归还
      isNeedReturn: ''
    },
    // 物品id
    shareId: '',
    // 订单id
    orderId: '',
    endUpdateAt: '',
    // 支付相关
    payment: {
      paymentState: '',
      paymentAt: ''
    },
    // 订单信息
    order: {
      orderTotalPoints: '',
      // 押积分合计
      orderDeposit: '',
      // 积分合计
      orderSharePoints: '',
      orderNum: ''
    },
    // 卖家信息
    sellUser: {
      sellName: ''
    },
    buttonList: {
      // 查看订单
      viewOrderButton: '',
      // 订单状态
      promptInformation: '',
      // 下单（线下交易按钮），未下单会显示1，其余状态会显示0
      orderCreateButton: '',
      // 取消订单按钮,下单后会显示1,其余状态显示0
      cancelButton: '',
      // 支付按钮，下单后，未支付的时候显示1
      paymentButton: '',
      // 删除订单按钮，订单取消后显示1
      deleteButton: ''
    },
    orderNumber: '',
    updateAt: ''
  })

  const [defalutAddress, setDefalutAddress] = useState<DefalutAddress>({
    addressName: '',
    addressMobile: '',
    addressDetail: '',
    addressId: ''
  })
  const [isOpened, setisOpened] = useState<boolean>(false) // 提示弹窗
  // 弹窗信息
  const [modalInfo, setmodalInfo] = useState({
    title: '',
    content: '',
    type: '',
    orderId: ''
  })

  const router = useRouter()
  const { orderId } = router.params
  const refOrderId = useRef(orderId)
  // 当用户点击去地址页面，选择后的地址
  useEffect(() => {
    if (Object.keys(address).length > 0) {
      setDefalutAddress(address)
      return
    }
  }, [address])

  // 查询地址，如果订单详情无地址，给默认地址
  const getAddressListNew = useCallback(() => {
    api['address/getAddressListNew']().then((ele) => {
      const data = ele.data
      if (data.length < 0) {
        return
      }
      const _defalutAddress = data.filter((item) => {
        return item.state === '1'
      })
      _defalutAddress.length > 0 && setDefalutAddress(_defalutAddress[0])
    })
  }, [])

  // 查询订单信息
  const getOrderDetail = useCallback(
    (flag = false) => {
      return api['itemSharing/getOrderDetail']({ orderId: refOrderId.current }).then((res) => {
        setOrderDetail(res.data[0])
        // 提交订单后，查询最新订单信息，调支付弹窗
        flag && setShowPay(true)
        const _address = res.data[0].address
        if (_address.addressMobile.length > 0) {
          setDefalutAddress(res.data[0].address)
        } else {
          getAddressListNew()
        }
      })
    },
    [getAddressListNew]
  )

  useEffect(() => {
    getOrderDetail()
  }, [getOrderDetail])

  const useMemoEndUpdateAt: CountDownReturn = useMemo(() => {
    const nowTime = countDown(Number(new Date(orderDetail.endUpdateAt)), Number(new Date()))
    return nowTime
  }, [orderDetail.endUpdateAt])

  // 提交订单,创建订单
  function submitOrder() {
    if (orderNum <= 0) {
      Taro.showToast({ title: '未选择商品数量', icon: 'none' })
      return
    } else if (orderDetail.shareDetail.inventory <= 0) {
      Taro.showToast({ title: '库存不足', icon: 'none' })
      return
    }
    const params = {
      shareId: orderDetail.shareId,
      orderId: orderDetail.orderId,
      addressId: defalutAddress.addressId,
      orderNum,
      orderSharePoints: orderDetail.shareDetail.sharePoints,
      orderDeposit: orderDetail.shareDetail.deposit,
      orderIsNeedReturn: orderDetail.shareDetail.isNeedReturn
    }
    api['itemSharing/createOrder'](params).then(() => {
      getOrderDetail(true)
    })
  }
  // 取消弹窗
  function onCancel() {
    setisOpened(false)
    if (modalInfo.type === 'orderDispute') {
      api['orderList/orderDispute']({ orderId: modalInfo.orderId, type: 2 }).then(() => {
        showToast('操作成功')
        setisOpened(false)
        getOrderDetail()
      })
    }
  }
  // 弹窗确定
  function onConfirm() {
    setisOpened(false)
    const _params: ConfirmParams = {
      type: '',
      orderId: ''
    }
    const type = modalInfo.type
    let url = ''
    switch (type) {
      case 'orderCancel': // 取消订单
        url = 'orderList/orderCancel'
        break
      case 'deleteOrder': // 删除订单
        url = 'orderList/deleteOrder'
        break
      case 'receiptAction': // 确定收货
        url = 'orderList/receiptAction'
        break
      case 'deliveryAction': // 发货
        url = 'orderList/deliveryAction'
        break
      case 'deliveryReturn': // 归还发货
        url = 'orderList/deliveryReturn'
        break
      case 'deliveryReturn': // 归还发货
        url = 'orderList/receiptReturn'
        break
      case 'orderDispute': // 纠纷选择
        _params.type = 1
        url = 'orderList/orderDispute'
        break
    }
    if (!url) return
    _params.orderId = modalInfo.orderId
    api[url](_params).then(() => {
      showToast('操作成功')
      getOrderDetail()
    })
  }
  return (
    <View className='editorder grey-bgc page-height'>
      {/* 待支付提示 */}
      {orderDetail.buttonList.viewOrderButton === '1' && (
        <View className='editorder-payoff white-bgc'>
          <View className='red-bgc'>
            <View className='editorder-payoff__status white-color'>
              <AtIcon value='alert-circle' size='20' color='#e2e2e2'></AtIcon>
              <Text className='editorder-payoff__status-msg'>
                {orderDetail.buttonList.promptInformation}
              </Text>
            </View>
            <View className='editorder-payoff__points'>支付积分：5</View>
          </View>
          {orderDetail.buttonList.paymentButton === '1' && (
            <View className='editorder-payoff__countDown flex'>
              请
              <AtCountdown
                isShowDay
                day={useMemoEndUpdateAt.day}
                hours={useMemoEndUpdateAt.hour}
                minutes={useMemoEndUpdateAt.minute}
                seconds={useMemoEndUpdateAt.second}
              />
              内完成支付，超时订单自动取消！
            </View>
          )}
        </View>
      )}

      {/* 收货信息 */}
      <View
        className='editorder-user white-bgc'
        onClick={() => {
          if (orderDetail.buttonList.viewOrderButton === '0') {
            Taro.navigateTo({ url: '/pages/Address/index' })
          }
        }}
      >
        <View className='editorder-user__title red-color'>收货地址</View>
        <View className='editorder-user__info'>
          <Text className='editorder-user__info-name'>姓名：{defalutAddress.addressName}</Text>
          <Text>联系电话：{defalutAddress.addressMobile}</Text>
        </View>
        <View className='editorder-user__address'>{defalutAddress.addressDetail}</View>
        {orderDetail.buttonList.viewOrderButton === '0' && (
          <AtIcon
            value='chevron-right'
            size='25'
            color='#bbbbbb'
            className='editorder-user__icon ct'
          ></AtIcon>
        )}
      </View>
      {/* 物品信息 */}
      <View className='editorder-items white-bgc'>
        <View className='editorder-items__title red-color'>物品信息</View>
        <View className='flex editorder-items-main'>
          <Image
            src={orderDetail.imagePath[0].imagePath}
            className='editorder-items__title-goodsimg'
          ></Image>
          <View className='editorder-items__info'>
            <View className='editorder-items__info-name'>{orderDetail.title}</View>
            <View className='editorder-items__info-integral'>
              积分：<Text className='red-color'>{orderDetail.shareDetail.sharePoints}</Text>
            </View>
            <View>
              押积分：<Text className='red-color'>{orderDetail.shareDetail.deposit}</Text>
            </View>
          </View>
          <View className='editorder-items__info-orderNum'>
            {orderDetail.buttonList.viewOrderButton === '0' ? (
              <AtInputNumber
                type='number'
                min={0}
                max={orderDetail.shareDetail.inventory as number}
                step={1}
                value={orderNum}
                onChange={(value) => {
                  setOrderNum(value)
                }}
              />
            ) : (
              <Text>× {orderDetail.order.orderNum}</Text>
            )}
          </View>
        </View>
        {orderDetail.buttonList.viewOrderButton === '1' && (
          <View>
            <View className='editorder-items__totalPoints'>
              积分合计：{orderDetail.order.orderSharePoints}
            </View>
            <View className='editorder-items__totalPoints'>
              押积分合计：{orderDetail.order.orderDeposit}
            </View>
          </View>
        )}
      </View>

      {/* 支付方式 */}
      {orderDetail.buttonList.viewOrderButton === '0' && (
        <View className='editorder-pay white-bgc'>
          <View className='editorder-pay__title red-color'>支付方式</View>
          <View className='editorder-pay__items tc-flex'>
            <AtIcon prefixClass='icon' value='jf' size='28' color='#febe36'></AtIcon>
            <View className='editorder-pay__items-mode'>
              <View className='mode-integral'>积分</View>
              <View className='mode-tips grey-color'>仅支持积分支付</View>
            </View>
            <AtIcon
              prefixClass='icon'
              value='checkbox'
              size='18'
              color='#febe36'
              className='editorder-pay__items-check ct'
            ></AtIcon>
          </View>
        </View>
      )}

      {/* 订单信息 */}
      {orderDetail.buttonList.viewOrderButton === '1' && (
        <View className='editorder-orderInfo white-bgc'>
          <View className='editorder-orderInfo__title red-color font32'>订单信息</View>
          <View className='editorder-orderInfo--common '>
            订单状态：{orderDetail.buttonList.promptInformation}
          </View>
          <View className='editorder-orderInfo--common '>订单编号：{orderDetail.orderNumber}</View>
          <View className='editorder-orderInfo--common '>创建日期：{orderDetail.updateAt}</View>
          <View className='editorder-orderInfo--common '>
            支付日期：{orderDetail.payment.paymentAt}
          </View>
          <View className='editorder-orderInfo__btm sb-flex'>
            <View
              className='tc-flex'
              onClick={() => {
                Taro.navigateTo({
                  url:
                    '/pages/ChartOnline/index?orderId=' +
                    orderDetail.orderId +
                    '&name=' +
                    orderDetail.sellUser.sellName
                })
              }}
            >
              <AtIcon prefixClass='icon' value='lxmj' size='20' color='#000'></AtIcon>
              <Text className='editorder-orderInfo__btm-touch'> 联系卖家</Text>
            </View>
            {/* 订单btn */}
            <OrderBtnState
              orderDetail={orderDetail}
              openPay={() => {
                setShowPay(true)
              }}
              // 打开弹窗设置提示内容
              openModal={(value) => {
                setmodalInfo(value)
                setisOpened(true)
              }}
            ></OrderBtnState>
          </View>
        </View>
      )}
      {/* 提交订单 */}
      {orderDetail.buttonList.viewOrderButton === '0' && (
        <View className='editorder-submit white-bgc tc-flex iphonex-safe-dis'>
          <View className='editorder-submit__points'>
            合计积分：<Text>{Number(orderDetail.shareDetail.sharePoints) * orderNum}</Text>
          </View>
          <View>
            合计押积分：<Text>{Number(orderDetail.shareDetail.deposit) * orderNum}</Text>
          </View>
          <View className='editorder-submit__btn orange-btn' onClick={submitOrder}>
            提交订单
          </View>
        </View>
      )}

      {/* 支付弹窗 */}
      {showPay && (
        <Payment
          orderDetail={orderDetail}
          closePay={(update) => {
            setShowPay(false)
            if (update) {
              getOrderDetail()
            }
          }}
        ></Payment>
      )}
      {/* 确认弹窗 */}
      <Modal
        title={modalInfo.title}
        content={modalInfo.content}
        cancelText='取消'
        confirmText='确定'
        onCancel={onCancel}
        onConfirm={onConfirm}
        isOpened={isOpened}
      ></Modal>
    </View>
  )
}

export default OrderDetails
